package com.ts.code.creator.util;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class CodeProperties {
    private String author;
    private String service;
    private String serviceAlias;
    private String retType;
    private String paramType;
    private List<EntityAlias> entityAliasList = new ArrayList<>();

    @JSONField(serialize = false)
    private Map<String, EntityAlias> controllerNameToEntityAlias;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class EntityAlias {
        private String controllerName;
        private String entityName;
        private String entityAlias;
    }

    public void add(String controllerName, String entityName, String entityAlias) {
        init();
        EntityAlias e = controllerNameToEntityAlias.get(controllerName);
        if (e == null) {
            e = new EntityAlias(controllerName, entityName, entityAlias);
            controllerNameToEntityAlias.put(controllerName, e);
            entityAliasList.add(e);
        } else {
            if (!e.getEntityName().equals(entityName) || !e.getEntityAlias().equals(entityAlias)) {
                e.setEntityName(entityName);
                e.setEntityAlias(entityAlias);
            }
        }
    }

    public EntityAlias getEntityAlias(String controllerName) {
        init();
        return controllerNameToEntityAlias.get(controllerName);
    }

    private void init() {
        if (controllerNameToEntityAlias == null) {
            controllerNameToEntityAlias = new HashMap<>();
            entityAliasList.forEach(t -> controllerNameToEntityAlias.put(t.getControllerName(), t));
        }
    }

}
